﻿//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2019年12月30日 20:32:56
//------------------------------------------------------------

namespace NKG_MVVM_UI
{
    /// <summary>
    /// 可绑定的属性，当其值改变时会判重，然后决定是否执行委托
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BindableProperty<T>
    {
        /// <summary>
        /// 定义当监测的值发生变化时会执行的委托
        /// </summary>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public delegate void ValueChangedHandler(T oldValue, T newValue);

        /// <summary>
        /// 声明一个委托对象
        /// </summary>
        public ValueChangedHandler OnValueChanged;

        private T _value;

        public T Value
        {
            get => _value;
            set
            {
                //进行值对比，如果不一样就更新值，并执行委托
                if (Equals(_value, value)) return;
                T old = _value;
                _value = value;
                ValueChanged(old, _value);
            }
        }

        /// <summary>
        /// 当值改变会执行的操作
        /// </summary>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        private void ValueChanged(T oldValue, T newValue)
        {
            OnValueChanged?.Invoke(oldValue, newValue);
        }

        public override string ToString()
        {
            return Value != null ? Value.ToString() : "null";
        }
    }
}